package com.jp.knowledge.util;

import com.jp.knowledge.db.DBHelper;
import com.jp.knowledge.model.NetLogModel;

import org.xutils.db.sqlite.WhereBuilder;

import java.util.List;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

import rx.Observer;

/**
 * Created by 528787067@qq.com on 2017/2/15.
 */

public class NetLogUtil {

    private static final int LOG_MAX_SIZE = 30;
    private static Observer<List<NetLogModel>> deleteObserver;
    private static Executor executor;

    public static void saveNetMsgToLocal(final NetLogModel netLogModel){
//        if(executor == null)
//            executor = Executors.newSingleThreadExecutor();
//        if(deleteObserver == null)
//            deleteObserver = new Observer<List<NetLogModel>>(){
//                @Override
//                public void onCompleted() {}
//                @Override
//                public void onError(Throwable e) {}
//                @Override
//                public void onNext(List<NetLogModel> netLogModels) {
//                    if(netLogModels.size() > LOG_MAX_SIZE){
//                        DBHelper.getInstance().delete(NetLogModel.class,
//                                WhereBuilder.b("id", "<=", netLogModels.get(netLogModels.size()-1).getId()-LOG_MAX_SIZE));
//                    }
//                }
//            };
//        executor.execute(new Runnable() {
//            @Override
//            public void run() {
//                DBHelper.getInstance().saveOrUpdate(netLogModel);
//                getNetMsgFromLocal(deleteObserver);
//            }
//        });
    }

    public static void getNetMsgFromLocal(Observer<List<NetLogModel>> observer){
        synchronized (observer) {
            DBHelper.getInstance().findAll(NetLogModel.class, observer);
        }
    }

    public static void clearNetLog(){
        DBHelper.getInstance().dropTable(NetLogModel.class);
    }
}
